package com.wrb.pwd.component;

import com.wrb.pwd.constant.Constant;
import com.wrb.pwd.utils.MD5Utils;

import javax.swing.*;
import java.awt.*;

/**
 * @author wrb
 * @date 2019/10/9 10:15
 */
public class PasswordUpdatePanel extends JPanel {

	private JLabel lbNewPassword, lbConfirmPassword, lbIMsg;

	private JTextField txtNewPassword, txtConfirmPassword;

	private JButton btnReg, btnCancel;

	public static PasswordUpdatePanel getInstance() {
		return Inner.INSTANCE;
	}

	private static class Inner {
		private static final PasswordUpdatePanel INSTANCE = new PasswordUpdatePanel();
	}

	private PasswordUpdatePanel() {
		super(null);

		lbNewPassword = new JLabel("新 密 码");
		lbConfirmPassword = new JLabel("确认密码");
		lbIMsg = new JLabel();

		txtNewPassword = new JPasswordField(20);
		txtConfirmPassword = new JPasswordField(20);

		btnReg = new JButton("记录");
		btnCancel = new JButton("清空");

		//验证密码，并把新密码放到内存中
		btnReg.addActionListener(e -> {
			//设置标签的文字是红色
			lbIMsg.setForeground(Color.RED);

			String pwdStr = txtNewPassword.getText();
			if (pwdStr == null || "".equals(pwdStr.trim())) {
				lbIMsg.setText("新密码不能为空");
				return;
			}
			String confirmPwdStr = txtConfirmPassword.getText();
			if (confirmPwdStr == null || "".equals(confirmPwdStr.trim())) {
				lbIMsg.setText("确认密码不能为空");
				return;
			}
			if (!pwdStr.equals(confirmPwdStr)) {
				lbIMsg.setText("新密码与确认密码不一致");
				return;
			}
			Constant.password = MD5Utils.md5(pwdStr);
			//设置标签的文字是绿色
			lbIMsg.setForeground(Color.GREEN);
			lbIMsg.setText("密码修改成功");
		});

		btnCancel.addActionListener(e -> init());

		lbNewPassword.setBounds(120, 60, 60, 25);
		txtNewPassword.setBounds(185, 60, 180, 25);
		lbConfirmPassword.setBounds(120, 100, 60, 25);
		txtConfirmPassword.setBounds(185, 100, 180, 25);
		lbIMsg.setBounds(120, 210, 180, 25);
		btnReg.setBounds(120, 240, 60, 25);
		btnCancel.setBounds(210, 240, 60, 25);

		this.add(lbNewPassword);
		this.add(txtNewPassword);
		this.add(lbConfirmPassword);
		this.add(txtConfirmPassword);
		this.add(lbIMsg);
		this.add(btnReg);
		this.add(btnCancel);
	}

	public void init() {
		this.txtNewPassword.setText("");
		this.txtConfirmPassword.setText("");
		this.lbIMsg.setText("");
	}


	public void setHomeButton(JButton jbHome) {
		jbHome.setBounds(300, 240, 60, 25);
		this.add(jbHome);
	}

	public static void main(String[] args) {
		JFrame jFrame = new JFrame();
		jFrame.add(PasswordUpdatePanel.getInstance());
		PasswordUpdatePanel.getInstance().setHomeButton(new JButton("首頁"));
		jFrame.setSize(500, 520);
//		this.setLocation(200, 100);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setVisible(true);
		//设置窗口大小不可更改
		jFrame.setResizable(false);

	}
}
